Skip to content

feat(security): add XSS sanitization and security headers#1455

Open
kelvinkipruto wants to merge 6 commits intomainfrom
ft/security-fixes
Open

feat(security): add XSS sanitization and security headers#1455
kelvinkipruto wants to merge 6 commits intomainfrom
ft/security-fixes

Conversation

@kelvinkipruto
Copy link
Copy Markdown
Contributor

Description

  • Sanitize user-provided embed HTML with xss library
  • Add Content-Security-Policy and other security headers
  • Normalize CORS/CSRF origins and set default allowed origin
  • Update HelplineCard, RowCard, and ActionBanner components to use sanitized embed code

Fixes # (issue)

Type of change

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)

Screenshots

Checklist:

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation

- Sanitize user-provided embed HTML with xss library
- Add Content-Security-Policy and other security headers
- Normalize CORS/CSRF origins and set default allowed origin
- Update HelplineCard, RowCard, and ActionBanner components to use sanitized embed code
@kilemensi
Copy link
Copy Markdown
Member

It's cool to sanitize @kelvinkipruto if it's not a lot of work. Remember, we're not getting content from end users i.e. the web like reddit. We're rendering content from a CMS managed and reviewed by trusted content editors.

@kelvinkipruto kelvinkipruto marked this pull request as ready for review April 17, 2026 12:44
@kelvinkipruto
Copy link
Copy Markdown
Contributor Author

@codex @claude Review

@claude
Copy link
Copy Markdown

claude bot commented Apr 21, 2026

Claude finished @kelvinkipruto's task in 2m 1s —— View job


PR Review: feat(security): add XSS sanitization and security headers

  • Gather context and understand the request
  • Read changed files
  • Analyze security implementation
  • Review component changes
  • Post comprehensive review feedback

Overall this is a solid, well-structured security PR. I have a few issues of varying severity to flag.


sanitizeEmbedHtml.js — Generally Good

The whitelist is thoughtfully constructed. A few notes:

iframe.src is allowed without URL protocol enforcement.
The xss library's built-in URL filtering applies to href but its behavior for src depends on whether the onTagAttr callback is customized. In xss@^1.0.15 with a custom whiteList, javascript: protocol in src is not automatically stripped. Add explicit URL validation for src:

onTagAttr(tag, name, value) {
  if (tag === "iframe" && name === "src") {
    try {
      const url = new URL(value);
      if (!["https:", "http:"].includes(url.protocol)) return ""; // strip
    } catch {
      return ""; // invalid URL
    }
  }
},

Fix this →

sandbox is not enforced on iframes.
The whitelist allows sandbox as an attribute but does not require it. An editor could paste an embed without a sandbox attribute, giving the iframe full browser permissions. Consider enforcing a default sandbox value via onTagAttr:

if (tag === "iframe" && name === "sandbox" && value === "") {
  return "allow-scripts allow-same-origin";
}

Or, if you want to ensure iframes are always sandboxed, add it in a post-processing step.


securityHeaders.mjs — Needs Attention

script-src 'unsafe-inline' https: largely defeats XSS protection.
This CSP allows inline scripts AND scripts from any HTTPS host. Combined with the XSS sanitization in this PR, there is a design tension: you're sanitizing HTML to prevent script injection but the CSP would allow inline scripts anyway. The comment notes MUI requires this, but this is worth revisiting — MUI v6 supports nonce-based CSP. This is a known limitation, but it should be documented explicitly and tracked as a follow-up item.

connect-src 'self' https: allows connections to any HTTPS URL in production. If the app doesn't need to call arbitrary third-party APIs from the browser, this should be scoped to specific domains (Payload CMS API, Sentry, etc.).

frame-ancestors 'self' and X-Frame-Options: SAMEORIGIN are redundant.
Not a bug — having both is correct for legacy browser compatibility. Just a note for awareness.

securityHeaders constant is evaluated at import time (line 67).
export const securityHeaders = getSecurityHeaders() captures process.env.NODE_ENV at module load. This is fine for a Next.js config but subtle. The exported getSecurityHeaders function is the safer API; the securityHeaders constant is a convenience that could surprise someone testing with a mocked NODE_ENV. Consider removing the pre-evaluated constant and only exporting the function, calling it in next.config.mjs.


Component Changes

HelplineEmbedDialog accepts unsanitized input.
The dialog (HelplineEmbedDialog.js) receives embedCode and renders it with dangerouslySetInnerHTML without sanitizing it. Both HelplineCard and RowCard currently pass a pre-sanitized value, but this creates a fragile contract — any future caller that passes raw CMS data directly to HelplineEmbedDialog will bypass sanitization silently.

Move the sanitization into HelplineEmbedDialog itself (or document clearly in a comment that callers must sanitize). Fix this →

No memoization for sanitization.
sanitizeEmbedHtml is called on every render in all three components. For typical embed strings this is negligible, but wrapping it in useMemo is cleaner and communicates that it's an expensive/intentional transformation:

const sanitizedEmbedCode = useMemo(() => sanitizeEmbedHtml(embedCode), [embedCode]);

payload.config.ts — Clean Improvement ✓

The refactor to normalizeOrigins, trailing-slash stripping, and the fallback to [defaultAllowedOrigin] when env vars are absent are all good changes. The serverURL fix (replace(/\/+$/, "") vs slice(0, -1)) is more robust.

One observation: normalizeOrigins deduplicates repeated slashes (replace(/\/+$/…)) but does not deduplicate repeated entries in the array. Not a bug, just worth noting.


On kilemensi's comment

The reviewer's point is valid — trusted CMS content is lower risk than user-generated content. That said, "defense in depth" is a legitimate reason to sanitize even trusted content (editor accounts can be compromised, CMS storage can be modified, etc.). The sanitization overhead is small and the protection is real.

What weakens the argument is the current CSP ('unsafe-inline' https:) — if you fix that, the sanitization becomes much more meaningful. As-is, the CSP gap limits the XSS protection provided by this PR.


Summary

Severity Issue
Medium iframe.src in sanitizer lacks protocol validation
Medium HelplineEmbedDialog doesn't sanitize its own input
Low CSP script-src 'unsafe-inline' https: is very broad
Low sandbox not enforced on iframes
Info securityHeaders module-level constant evaluated at import
payload.config.ts refactor is a clear improvement
Security headers are a welcome addition

@kilemensi
Copy link
Copy Markdown
Member

Remember, we're not getting content from end users i.e. the web like reddit. We're rendering content from a CMS managed and reviewed by trusted content editors.

My question still remains @kelvinkipruto , why go through all of this if the content comes from our CMS which we have full control of? The content doesn't come from the wild web out there.

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: a99adb6537

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +55 to +59
if (nodeEnv === "production") {
// HSTS is intentionally production-only so local HTTP development and
// non-TLS preview setups do not get sticky HTTPS behavior.
headers.push({
key: "Strict-Transport-Security",
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Guard HSTS behind explicit TLS deployment flag

Strict-Transport-Security is currently enabled whenever NODE_ENV === "production", but production mode is commonly used for HTTP-only preview/staging deployments too. In those environments, sending HSTS causes browsers to cache an HTTPS-only policy for the host, which can make the preview site inaccessible and persists beyond a single session. Since this code intends to avoid non-TLS preview stickiness, it should be gated by an explicit HTTPS/TLS deployment signal rather than NODE_ENV alone.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants